<template>
  <div class="chat-msg" v-if="user.show">
    <el-scrollbar ref="chat-box">
      <div class="chat-list" v-for="(item,index) in chatMsg">
        <div :class="item.sendPerson == user.receiverPerson ?'chat-list-left':'chat-list-right'">
          <img :src="item.avatar" class="list-img"/>
          <div :class="item.sendPerson == user.receiverPerson ? 'left-msg' : 'right-msg'">
            <span class="msg-content">
              {{ item.msg }}
            </span>
          </div>
        </div>
      </div>
    </el-scrollbar>
    <div class="chat-boom">

      <div class="chat-tool">
        <el-popover placement="top-start" width="400" trigger="click" class="emoBox">
          <div class="emotionList">
            <a href="javascript:void(0);" @click="getEmoji(index)" v-for="(item,index) in faceList" :key="index"
               class="emotionItem">{{ item }}</a>
          </div>
          <span id="emojiBtn" class="emotionSelect" slot="reference">
             <img :src="require('@/assets/emoji.png')" alt="">
          </span>
        </el-popover>
      </div>


      <el-input class="textarea" resize="none" type="textarea" :rows="7" placeholder="输入发送消息" v-model.trim="msg" ref="msg">

      </el-input>

      <el-button type="primary" :disabled="this.msg ===''" @click="send" plain @keyup.enter="keyDown(e)"
                 class="send-button">发送(S)
      </el-button>
    </div>
  </div>
</template>

<script>
import {sendMsg, chatMsgList} from '@/api/chat/index'
import emoji from '@/assets/emoji.json'
export default {
  name: "index",
  computed: {
    monitor() {
      return this.$store.state.chatMsg
    }
  },
  props: {
    obj: {
      require: true,
      default() {
        return {};
      },
      type: Object
    },
  },
  data() {
    return {
      user: {
        receiverPerson: '',
        show: false
      },
      chatMsg: [],
      msg: '',
      faceList: []
    }
  },
  methods: {
    //发送消息
    send() {
      let sendObj = {
        receiverPerson: this.user.receiverPerson,
        msg: this.msg,
        msgType: 0
      }
      sendMsg(sendObj).then(res => {
        this.queryChatMsgList()
      }).catch(error => {

      })
      this.msg = ''
    },
    //获取消息列表
    queryChatMsgList() {
      chatMsgList(this.user.receiverPerson).then(res => {
        if (res.code === 200) {
          this.chatMsg = res.data
        }
        this.contentMiddle()
      }).catch(error => {

      })
    },
    //聊天内容置于最底部
    contentMiddle() {
      this.$nextTick(() => {
        let chatBox = this.$refs['chat-box']
        chatBox.wrap.scrollTop = chatBox.wrap.scrollHeight
      })
    },
    // 回车键快捷发送
    keyDown(e) {
      if ((e.keyCode === 13 || e.keyCode === 100) && this.msg !== '') {
        this.send()
      }
    },
    //语音播报
    /**
     * @param sentence：要说的句子
     * @param pitch: 音调，取值范围(0 - 2) 默认值：1
     * @param rate: 语速，取值范围(0.1 - 10) 默认值：1
     */
    startTextToSpeech(sentence, pitch, rate) {
      const speech  = new window.SpeechSynthesisUtterance()
      speech.text = sentence
      speech.rate = rate
      speech.pitch = pitch
      speech.lang = 'zh-CN'
      window.speechSynthesis.cancel()
      window.speechSynthesis.speak(speech)
    },
    //获取表情
    getEmoji(index) {
      let msg = this.$refs['msg']
      let str = this.faceList[index]
      this.msg = msg._props['value'].concat(str)
    }
  },
  mounted() {
    //绑定键盘按下事件
    window.addEventListener("keydown", this.keyDown);
    for (let i in emoji) {//读取json文件保存数据给数组
      this.faceList.push(emoji[i].char);
    }
  },
  destroyed() {
    //销毁键盘按下事件
    window.removeEventListener("keydown", this.keyDown, false)
    window.speechSynthesis.cancel()
  },
  watch: {
    obj(newValue) {
      this.user = Object.assign(newValue)
      this.queryChatMsgList()
    },

    //监听对方发送的数据
    monitor() {
      // 必须处于聊天的页面才进行刷新
      if (this.$route.path === "/chat" && this.user.receiverPerson !== '' && this.$store.state.chatMsg.code === 10002) {
        //新消息来了就退出正在播放的语音
        window.speechSynthesis.cancel()
        this.startTextToSpeech(this.$store.state.chatMsg.msg,1,1)
        this.queryChatMsgList()
        this.contentMiddle()
      }
    }
  }
}
</script>

<style scoped lang="scss">
.chat-msg {
  height: 100%;
  display: flex;
  background: rgb(247, 247, 247);
  flex-direction: column;
  justify-content: space-between;
}

.chat-list {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-list-left {
  padding: 20px;
  display: flex;
  flex-direction: row;
}

.list-img {
  width: 40px;
  height: 40px;
  border-radius: 5px;
}

.left-msg {
  margin-left: 5px;
  background: #ffffff;
  font-size: 15px;
  border-radius: 6px;
  max-width: 200px;
  word-wrap: break-word;
}

.chat-list-right {
  padding: 20px;
  display: flex;
  flex-direction: row-reverse;
}

.right-msg {
  margin-right: 5px;
  font-size: 15px;
  border-radius: 6px;
  max-width: 200px;
  word-wrap: break-word;
  background-color: #4ccb69;
}

.chat-boom {
  position: relative;
}

.send-button {
  float: right;
  position: absolute;
  bottom: 10px;
  right: 10px;
}

.msg-content {
  display: block;
  padding: 10px 10px 10px 10px;
}

#emojiBtn:hover {
  background-color: white;
}

.emotionList {
  display: flex;
  flex-wrap: wrap;
  padding: 5px;
}

.emotionItem {
  width: 10%;
  font-size: 20px;
  text-align: center;
}

/*包含以下四种的链接*/
.emotionItem {
  text-decoration: none;
}

/*正常的未被访问过的链接*/
.emotionItem:link {
  text-decoration: none;
}

/*已经访问过的链接*/
.emotionItem:visited {
  text-decoration: none;
}

/*鼠标划过(停留)的链接*/
.emotionItem:hover {
  text-decoration: none;
}

/* 正在点击的链接*/
.emotionItem:active {
  text-decoration: none;
}

.chat-tool {
  width: 100%;
  height: 40px;
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  grid-template-areas: 'a b';
  justify-items: center;
  align-items: center;
  background-color: #d9d9d9;
}

.emotionSelect {
  display: block;
  width: 20px;
  height: 20px;
  grid-area: a;
  border-radius: 10px;
  img{
    width: 100%;
    height: 100%;
    background-size: 100%;
  }
}
</style>